<template>
    <view class="u-wrap">
        <u-toast ref="uToast" /><u-no-network></u-no-network>
        <u-navbar safeAreaInsetTop fixed placeholder :bgColor="CateStyle == 4 ? '#e9f6ec' : '#fff'">
            <view slot="left">
                <u-search :show-action="true" shape="round" v-model="searchKey"
                    :bgColor="CateStyle == 4 ? '#fff' : '#f2f2f2'" actionText="搜索" placeholder="请输入搜索内容" @custom="goSearch"
                    @search="goSearch"></u-search>
            </view>
            <u-icon name="scan" color="#fff" size="16" slot="right"></u-icon>
        </u-navbar>

        <view class="coreshop-padding-10" v-if="CateStyle == 1">
            <view v-for="(item, index) in tabbar" :key="index" @click="goClass(item.id)">
                <u--image width="100%" height="195px" :src="item.imageUrl" :showLoading="false"></u--image>
                <view class="coreshop-text-center coreshop-padding-top-10 coreshop-padding-bottom-10">
                    {{ item.name }}
                </view>
            </view>
        </view>
        <view class="coreshop-padding-10" v-if="CateStyle == 2">
            <div class="col3Box" v-for="(item, index) in tabbar" :key="index" @click="goClass(item.id)">
                <u--image width="100%" height="80px" :src="item.imageUrl" :showLoading="false"></u--image>
                <view class="coreshop-text-center coreshop-padding-top-15 coreshop-padding-bottom-15 coreshop-font-sm">
                    {{ item.name }}
                </view>
            </div>
        </view>
        <view class="u-menu-wrap coreshop-flex-direction-row" v-if="CateStyle == 3">
            <scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop">
                <view v-for="(item, index) in tabbar" :key="index" class="u-tab-item"
                    :class="[current == index ? 'u-tab-item-active' : '']" :data-current="index"
                    @tap.stop="swichMenu(index)">
                    <text class="u-line-1">{{ item.name }}</text>
                </view>
            </scroll-view>
            <block v-for="(item, index) in tabbar" :key="index">
                <scroll-view scroll-y class="right-box" v-if="current == index">
                    <view class="coreshop-padding-10">
                        <coreshop-advert code="TplIndexBanner1"></coreshop-advert>
                        <view class="class-item">
                            <view class="item-title">
                                <text>{{ item.name }}</text>
                            </view>
                            <view class="item-container coreshop-flex-direction-row">
                                <view class="thumb-box" v-for="(item1, index1) in item.child" :key="index1"
                                    @click="goClass(item1.id)">
                                    <u--image width="60px" height="60px" :src="item1.imageUrl"
                                        :showLoading="false"></u--image>
                                    <view class="item-menu-name">{{ item1.name }}</view>
                                </view>
                            </view>
                        </view>
                    </view>
                </scroll-view>
            </block>
        </view>
        <view class="u-menu-wrap coreshop-flex-direction-row" v-if="CateStyle == 4">
            <view class="main" :style="'height:' + scorllH + 'px;'">
                <view class="content" :style="'height:' + scorllH + 'px;'">
                    <scroll-view class="menus" scroll-with-animation scroll-y :scroll-top="headerH"
                        :style="'height:' + scorllH + 'px;'">
                        <view class="wrapper">
                            <view class="menu" :id="`menu-${item.id}`" :class="{ 'current': item.id === currentCateId }"
                                v-for="(item, index) in menus" :key="index" @tap="handleMenuTap(item.id, index)">
                                <text>{{ item.name }}</text>
                            </view>
                        </view>
                    </scroll-view>
                    <scroll-view class="goods" scroll-with-animation scroll-y :scroll-top="headerH"
                        :style="'height:' + scorllH + 'px;'" @scrolltolower="scrolltolower">
                        <u-sticky v-if="menuChilds">
                            <view class="coreshop-bg-white coreshop-padding-left-10">
                                <u-tabs :list="menuChilds" :current="childCurrent"
                                    :activeStyle="{ color: '#303133', fontWeight: 'bold', transform: 'scale(1.05)', fontSize: '14px' }"
                                    :inactiveStyle="{ color: '#606266', transform: 'scale(1)', fontSize: '14px' }"
                                    @change="clickChange"></u-tabs>
                            </view>
                        </u-sticky>

                        <view class="coreshop-padding-10">
                            <coreshop-advert code="TplIndexBanner1" showTitle="true"></coreshop-advert>
                        </view>

                        <view class="wrapper">

                            <view class="list">
                                <view class="category" v-for="(good, key) in goodsList" :key="key" :id="`cate-${good.id}`">
                                    <view class="items">
                                        <view class="good">
                                            <view class="image">
                                                <u--image :showLoading="true" :src="good.image" width="83px" height="83px"
                                                    radius="4px" @click="goGoodsDetail(good.id)"></u--image>
                                            </view>
                                            <view class="right">
                                                <text class="u-line-2" @tap="goGoodsDetail(good.id)">{{ good.name }}</text>
                                                <u--text type="info" size="12px" lines="1" :text="good.brief"></u--text>
                                                <!--<text class="tips u-line-1" @tap="goGoodsDetail(good.id)">{{ good.brief }}</text>-->
                                                <view class="price_and_action">
                                                    <text class="price">￥{{ good.price }}</text>
                                                    <view class="btn-group">
                                                        <button type="primary" class="btn property_btn" hover-class="none"
                                                            size="mini" @tap="showGoodSkuModal(good)">
                                                            选规格
                                                        </button>
                                                    </view>
                                                </view>
                                            </view>
                                        </view>
                                    </view>
                                </view>
                                <u-loadmore :status="loadStatus" :icon-type="iconType" :load-text="loadText" margin-top="20"
                                    margin-bottom="20" />
                            </view>
                        </view>
                    </scroll-view>
                </view>
                <!-- 购物车栏 begin -->
                <view class="cart-box">
                    <view class="mark" @tap="redirectCart()">
                        <image src="/static/images/common/cart.png" class="cart-img"></image>
                        <view class="tag">{{ cartNums }}</view>
                    </view>
                    <view class="price">￥{{ cartMoney }}</view>
                    <button type="primary" class="pay-btn" @tap="redirectCart()" :disabled="cartNums <= 0">去结算</button>
                </view>
                <!-- 购物车栏 end -->
            </view>

            <vk-data-goods-sku-popup ref="skuPopup" v-model="skuKey" border-radius="20" :amount-type="0"
                :localdata="goodsSkuInfo" :mode="skuMode" @open="onOpenSkuPopup" @close="onCloseSkuPopup"
                @add-cart="addCart" @buy-now="buyNow"></vk-data-goods-sku-popup>
        </view>

        <view class="u-menu-wrap coreshop-flex-direction-row" style="flex-direction: column;" v-if="CateStyle == 5">
            <!-- 全部一级分类 -->
            <view class="primary-classification">
                <scroll-view class="primary-view" scroll-x="true" scroll-with-animation :scroll-left="scrollLeft">
                    <view :class="[{ 'active': index == primaryClassificationIndex }, 'menu-box classification-box']"
                        v-for="(item, index) in menus" :key="index" @click="hanldePrimaryClassificationChange(index)">
                        <image class="img" v-if="index != 0" :src="item.imageUrl"></image>
                        <image class="img" v-else
                            src="https://ts1.cn.mm.bing.net/th/id/R-C.3562db2b97df44ad0a2913367e923bc9?rik=F0gPEgEKbhChlw&riu=http%3a%2f%2fpic.962.net%2fup%2f2016-10%2f14760807179493223.gif&ehk=1QnaRGwQ3oUxW2TtYQHyQM5fm9qkakLLshGCLtGyzE0%3d&risl=&pid=ImgRaw&r=0">
                        </image>
                        <view class="name">{{ item.name }}</view>
                    </view> 
                </scroll-view>
                <view class="primary-classification-all" @click="handleShowPrimaryClassification">
                    <view class="tit">全部</view>
                    <u-icon name="grid" color="#1aad19" size="20"></u-icon>
                </view>
            </view>
            <!-- 全部分类弹框 -->
            <view class="all-primary-popup" v-show="showPrimaryClassification">
                <view class="mask" @click="hanldeClosePopup"></view>
                <view class="list-box">
                    <view class="title-box">
                        <view class="tit">全部分类</view>
                        <view class="close" @click="hanldeClosePopup"><u-icon name="close"></u-icon></view>
                    </view>
                    <view class="menu-layout">
                        <view :class="[{ 'active': index == primaryClassificationIndex }, 'menu-box']"
                            v-for="(item, index) in menus" :key="index" @click="hanldePrimaryClassificationChange(index)">
                            <image class="img" :src="item.imageUrl"></image>
                            <view class="name">{{ item.name }}</view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 二级分类 -->
            <view class="main" :style="'height:' + scorllH + 'px;'"> 
                <view class="content" :style="'height:' + scorllH + 'px;'">
                    <scroll-view class="menus" scroll-with-animation scroll-y :scroll-top="headerH"
                        :style="'height:' + scorllH + 'px;'">
                        <view class="wrapper">
                            <view class="menu" :id="`menu-${item.id}`" :class="{ 'current': item.id === currentCateId }"
                                v-for="(item, index) in secondaryClassification" :key="index"
                                @tap="handleMenuTapNew(item.id)">
                                <view class="tit-box">
                                    <image class="tip" v-if="index == 1"
                                        src="https://ts1.cn.mm.bing.net/th/id/R-C.3562db2b97df44ad0a2913367e923bc9?rik=F0gPEgEKbhChlw&riu=http%3a%2f%2fpic.962.net%2fup%2f2016-10%2f14760807179493223.gif&ehk=1QnaRGwQ3oUxW2TtYQHyQM5fm9qkakLLshGCLtGyzE0%3d&risl=&pid=ImgRaw&r=0">
                                    </image>
                                    <text>{{ item.name }}</text>
                                </view>
                            </view>
                        </view>
                    </scroll-view>
                    <view class="goods">
                        <!-- 三级分类 -->
                        <u-sticky v-if="menuChilds.length > 1">
                            <view class="sticky-box">
                                <scroll-view class="sticky-view" scroll-x="true" scroll-with-animation
                                    :scroll-left="scrollLeftSticky">
                                    <view :class="[{ 'active': index == childCurrent }, 'item']"
                                        @click="hanldeThreeClassification(item.id, index)"
                                        v-for="(item, index) in menuChilds" :key="item.id">
                                        <view class="name">{{ item.name }}</view>
                                    </view>
                                </scroll-view>
                                <view class="icon" v-if="menuChilds.length > 2" @click="handleShowThreeClassificationPopup">
                                    <u-icon v-if="!showThreeClassification" name="arrow-down" font-size="25"></u-icon>
                                    <u-icon v-else name="arrow-up" font-size="25"></u-icon>
                                </view>
                            </view>
                        </u-sticky>
                        <!-- 三级分类弹框 -->
                        <view class="sticky-popup-box" v-show="showThreeClassification">
                            <view class="mask" @click="showThreeClassification = !showThreeClassification"></view>
                            <view class="popup-layout">
                                <view :class="[{ 'active': index == childCurrent }, 'popup']"
                                    v-for="item, index in menuChilds" :key="item.id"
                                    @click="hanldeThreeClassification(item.id, index)">
                                    {{ item.name }}
                                </view>
                            </view>
                        </view>
                        <scroll-view class="goods" scroll-with-animation :scroll-y="showThreeClassification ? false : true"
                            :scroll-top="headerH"
                            :style="'height:' + parseInt(Number(scorllH) - (menuChilds.length > 1 ? 45 : 0)) + 'px;'"
                            @scrolltolower="scrolltolower" :show-scrollbar="false">
                            <!-- <view class="coreshop-padding-10">
                                <coreshop-advert code="TplIndexBanner1" showTitle="true"></coreshop-advert>
                            </view> -->

                            <view class="wrapper">

                                <view class="list">
                                    <view class="category" v-for="(good, key) in goodsList" :key="key"
                                        :id="`cate-${good.id}`">
                                        <view class="items">
                                            <view class="good">
                                                <view class="image">
                                                    <u--image :showLoading="true" :src="good.image" width="83px"
                                                        height="83px" radius="4px"
                                                        @click="goGoodsDetail(good.id)"></u--image>
                                                </view>
                                                <view class="right">
                                                    <text class="u-line-2" @tap="goGoodsDetail(good.id)">{{ good.name
                                                    }}</text>
                                                    <u--text type="info" size="12px" lines="1" :text="good.brief"></u--text>
                                                    <!--<text class="tips u-line-1" @tap="goGoodsDetail(good.id)">{{ good.brief }}</text>-->
                                                    <view class="price_and_action">
                                                        <text class="price">￥{{ good.price }}</text>
                                                        <view class="btn-group">
                                                            <button type="primary" class="btn property_btn"
                                                                hover-class="none" size="mini"
                                                                @tap="showGoodSkuModal(good)">
                                                                选规格
                                                            </button>
                                                        </view>
                                                    </view>
                                                </view>
                                            </view>
                                        </view>
                                    </view>
                                    <u-loadmore :status="loadStatus" :icon-type="iconType" :load-text="loadText"
                                        margin-top="20" margin-bottom="20" />
                                </view>
                            </view>
                        </scroll-view>
                    </view>
                </view>
                <!-- 购物车栏 begin -->
                <view class="cart-box">
                    <view class="mark" @tap="redirectCart()">
                        <image src="/static/images/common/cart.png" class="cart-img"></image>
                        <view class="tag">{{ cartNums }}</view>
                    </view>
                    <view class="price">￥{{ cartMoney }}</view>
                    <button type="primary" class="pay-btn" @tap="redirectCart()" :disabled="cartNums <= 0">去结算</button>
                </view>
                <!-- 购物车栏 end -->
            </view>

            <vk-data-goods-sku-popup ref="skuPopup" v-model="skuKey" border-radius="20" :amount-type="0"
                :localdata="goodsSkuInfo" :mode="skuMode" @open="onOpenSkuPopup" @close="onCloseSkuPopup"
                @add-cart="addCart" @buy-now="buyNow"></vk-data-goods-sku-popup>


        </view>

        <!-- 登录提示 -->
        <coreshop-login-modal></coreshop-login-modal>
    </view>
</template>
<script>
import { mapState } from 'vuex';
export default {

    data() {
        return {
            tabbar: [],
            scrollTop: 0, //tab标题的滚动条位置
            current: 0, // 预设当前项的值
            menuHeight: 0, // 左边菜单的高度
            menuItemHeight: 0, // 左边菜单item的高度,
            beans: [],
            isChild: false,
            searchKey: '',

            headerH: 0,
            scorllH: 0, //滚动区域全屏
            cartNums: 0, // 购物车数量
            cartMoney: 0, // 购物车数量
            menus: [],//所有分类
            menuChilds: [], //当前分类下子集
            needCurrentCateId: 0, //仿点餐模式下应该获取大类还是小类数据
            childCurrent: 0, //子集默认选中下标

            goodsList: [], //所有商品
            menuScrollIntoView: '',
            good: {},
            currentCateId: 0,//默认分类
            scrollTop: 0,
            loadStatus: 'loadmore',
            loadIconType: 'flower',
            loadText: {
                loadmore: '轻轻上拉',
                loading: '努力加载中',
                nomore: '实在没有了'
            },
            type: 2, // 1加入购物车 2购买
            cartType: this.$globalConstVars.paymentType.common,
            page: 1,
            limit: 10,
            // 是否打开SKU弹窗
            skuKey: false,
            // SKU弹窗模式
            skuMode: 1,
            // 后端返回的商品信息
            goodsSkuInfo: {},
            // 一级分类索引
            primaryClassificationIndex: 0,
            scrollLeft: 0,
            showPrimaryClassification: false,
            // 二级分类
            secondaryClassification: [],
            showThreeClassification: false,
            scrollLeftSticky: 0,
            contentScrollW: 0,
            stickyViewW:0,
        }
    },
    computed: {
        ...mapState({
            hasLogin: state => state.hasLogin,
            userInfo: state => state.userInfo,
        }),
        hasLogin: {
            get() {
                return this.$store.state.hasLogin;
            },
            set(val) {
                this.$store.commit('hasLogin', val);
            }
        },
        userInfo: {
            get() {
                return this.$store.state.userInfo;
            },
            set(val) {
                this.$store.commit('userInfo', val);
            }
        },
        CateStyle() {
            return this.$store.state.config.cateStyle ? this.$store.state.config.cateStyle : 3;
        }
    },
    onLoad() {
        uni.getSystemInfo({
            success: (e) => {
                // #ifndef MP
                this.StatusBar = e.statusBarHeight;
                if (e.platform == 'android') {
                    this.headerH = e.statusBarHeight + 50;
                } else {
                    this.headerH = e.statusBarHeight + 45;
                };
                // #endif 
                this.scorllH = parseInt(e.windowHeight - e.statusBarHeight - 50 - 90);
            }
        })
        // 获取购物车数量
        if (this.$store.state.config.cateStyle == 5) {
            this.goodsList = [];
            this.page = 1;
            this.limit = 10;
            this.categories();
            //this.getCartNums();
        } else {
            this.categories();
        }
    },
    onShow() {
        // 获取购物车数量
        if (this.$store.state.config.cateStyle == 5) {
            this.getCartNums();
        }
    },
    methods: {
        hanldePrimaryClassificationChange(index) { 
            if (this.primaryClassificationIndex != index) {
                this.primaryClassificationIndex = index; 
                this.scrollLeft = this.menus[index].left - this.contentScrollW / 2 + this.menus[index].width / 2;

                this.showPrimaryClassification = false; 
                this.secondaryClassification = this.menus[index].child || []; 
                this.currentCateId = this.menus[index].child[0].id;
                this.needCurrentCateId = this.menus[index].child[0].id;
                this.menuChilds = this.menus[index].child[0].child;
                this.showThreeClassification = false;
                this.handleMenuTapNew(this.currentCateId);
            }
        },
        handleShowPrimaryClassification() {
            this.showPrimaryClassification = true;
        },
        handleMenuTapNew(id) {
            const _this = this;
            _this.scrollLeftSticky = 0;
            let menu = _this.menus[_this.primaryClassificationIndex].child.filter((res) => res.id == id);
            _this.needCurrentCateId = menu[0].id;
            _this.currentCateId = menu[0].id;
            _this.menuChilds = menu[0].child || [];
            this.page = 1;
            this.goodsList = [];
            if (_this.menuChilds.length > 0 && _this.menuChilds[0].id != 0) {
                this.menuChilds.unshift({
                    id: 0,
                    imageUrl: "",
                    name: "全部",
                    sort: 0,
                });
            }
            _this.childCurrent = 0;
            _this.headerH = 0;
            _this.getGoods();
        },
        hanldeClosePopup() {
            this.showPrimaryClassification = false;
        },
        handleShowThreeClassificationPopup() {
            this.showThreeClassification = !this.showThreeClassification;
        },
        hanldeThreeClassification(id, index) {
            if (this.childCurrent != index) {
                this.childCurrent = index;
                this.scrollLeftSticky = index * 88 - this.stickyViewW / 2 + 88 /2;
                if (id != 0) {
                    this.needCurrentCateId = id;
                } else {
                    this.needCurrentCateId = this.currentCateId;
                }
                if (this.showThreeClassification) {
                    this.showThreeClassification = !this.showThreeClassification
                }

                this.page = 1;
                this.goodsList = [];
                this.getGoods();
            }
        },
        // 点击左边的栏目切换
        async swichMenu(index) {
            if (index == this.current) return;
            this.current = index;
            // 如果为0，意味着尚未初始化
            if (this.menuHeight == 0 || this.menuItemHeight == 0) {
                await this.getElRect('menu-scroll-view', 'menuHeight');
                await this.getElRect('u-tab-item', 'menuItemHeight');
            }
            // 将菜单菜单活动item垂直居中
            this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
        },
        // 获取一个目标元素的高度
        getElRect(elClass, dataVal) {
            new Promise((resolve, reject) => {
                const query = uni.createSelectorQuery().in(this);
                query.select('.' + elClass).fields({ size: true }, res => {
                    // 如果节点尚未生成，res值为null，循环调用执行
                    if (!res) {
                        setTimeout(() => {
                            this.getElRect(elClass);
                        }, 10);
                        return;
                    }
                    this[dataVal] = res.height;
                }).exec();
            })
        },
        goClass(catId) {
            uni.navigateTo({
                url: '/pages/category/list/list?id=' + catId
            });
        },
        goSearch() {
            if (this.searchKey != '') {
                this.$u.route('/pages/category/list/list?key=' + this.searchKey);
            } else {
                this.$refs.uToast.show({ message: '请输入查询关键字', type: 'warning', })
            }
        },
        categories() {
            this.$u.api.categories().then(res => {
                if (res.status) {
                    this.tabbar = res.data;

                    if (this.$store.state.config.cateStyle == 4) {
                        this.menus = res.data;
                        if (res.data.length > 0) {
                            for (var i = 0; i < res.data.length; i++) {
                                if (res.data[i].child) {
                                    let item = {
                                        id: 0,
                                        imageUrl: "",
                                        name: "全部",
                                        sort: 0,
                                    }
                                    res.data[i].child.unshift(...[item])
                                }
                            }
                            this.currentCateId = res.data[0].id;
                            this.needCurrentCateId = res.data[0].id;
                            this.menuChilds = res.data[0].child;
                            this.getGoods();
                        }

                    } else if (this.$store.state.config.cateStyle == 5) {
                        this.menus = res.data;
                        this.secondaryClassification = res.data[0].child || [];

                        this.currentCateId = res.data[0].child[0].id;
                        this.needCurrentCateId = res.data[0].child[0].id;
                        this.menuChilds = res.data[0].child[0].child;
                        this.menuChilds.unshift({
                            id: 0,
                            imageUrl: "",
                            name: "全部",
                            sort: 0,
                        });
                        this.getGoods();
                    }
                    this.$nextTick(() => {
                        const query = uni.createSelectorQuery().in(this);
                        query.select('.primary-view').boundingClientRect(data => { 
                            this.contentScrollW = data.width;
                        }).exec();
                        query.select('.sticky-view').boundingClientRect(data => { 
                            this.stickyViewW = data.width;
                        }).exec();
                        query.selectAll('.classification-box').boundingClientRect(data => {
                            let dataLen = data.length;
                            for (let i = 0; i < dataLen; i++) {
                                //  scroll-view 子元素组件距离左边栏的距离 还有宽度  
                                this.$set(this.menus[i], 'left', data[i].left)
                                this.$set(this.menus[i], 'width', data[i].width) 
                            }
                        }).exec();
                    })

                }
            });
        },
        // 打开sku弹出
        openSkuPopup() {
            this.skuKey = true;
        },
        closeSkuPopup() {
            this.skuKey = false;
        },
        // sku组件监听
        onOpenSkuPopup() {
            //console.log("监听 - 打开sku组件");
        },
        onCloseSkuPopup() {
            //console.log("监听 - 关闭sku组件");
        },
        showGoodSkuModal(item) {
            if (item.id) {
                this.getGoodsDetail(item.id);
            }
        },
        // 获取商品详情
        getGoodsDetail(goodsId) {
            uni.showLoading({
                title: '加载中'
            });
            let _this = this;
            let data = {
                id: goodsId,
                data: true
            }
            // 如果用户已经登录 要传用户token
            let userToken = this.$db.get("userToken");
            if (userToken) {
                this.$u.api.goodsDetailByToken(data).then(res => {
                    if (res.status == true) {
                        _this.goodsSkuInfo = res.data.skuList;
                        _this.openSkuPopup();
                        setTimeout(function () {
                            uni.hideLoading();
                        }, 1000);
                    } else {
                        _this.$refs.uToast.show({
                            message: res.msg, type: 'error', complete: function () {
                                uni.navigateBack({
                                    delta: 1
                                });
                            }
                        })
                        uni.hideLoading();
                    }
                })
            } else {
                this.$u.api.goodsDetail(data).then(res => {
                    if (res.status == true) {
                        _this.goodsSkuInfo = res.data.skuList;
                        _this.openSkuPopup();
                        setTimeout(function () {
                            uni.hideLoading();
                        }, 1000);
                    } else {
                        _this.$refs.uToast.show({
                            message: res.msg, type: 'error', complete: function () {
                                uni.navigateBack({
                                    delta: 1
                                });
                            }
                        })
                        uni.hideLoading();
                    }
                })
            }
        },
        // 加入购物车按钮
        addCart(selectShop) {
            var that = this;
            uni.showLoading({
                title: '加载中'
            });
            if (!this.hasLogin) {
                uni.hideLoading();
                this.$store.commit('showLoginTip', true);
                return false;
            }
            if (selectShop.buy_num > 0) {
                let data = {
                    productId: selectShop._id,
                    nums: selectShop.buy_num,
                    type: 1,
                }
                this.$u.api.addCart(data).then(res => {
                    if (res.status) {
                        uni.hideLoading();
                        that.getCartNums(); // 获取购物车数量
                        that.$refs.uToast.show({ message: res.msg, type: 'success' });
                    } else {
                        that.$u.toast(res.msg);
                        uni.hideLoading();
                    }
                });
            }
            that.closeSkuPopup();
        },
        // 立即购买
        buyNow(selectShop) {
            var that = this;
            uni.showLoading({
                title: '加载中'
            });
            if (!this.hasLogin) {
                uni.hideLoading();
                this.$store.commit('showLoginTip', true);
                return false;
            }
            if (selectShop.buy_num > 0) {
                let data = {
                    productId: selectShop._id,
                    nums: selectShop.buy_num,
                    type: 2,
                    cartType: this.cartType
                }
                this.$u.api.addCart(data).then(res => {
                    if (res.status) {
                        let cartIds = res.data;
                        that.$u.route('/pages/placeOrder/index/index?cartIds=' + JSON.stringify(cartIds));
                        uni.hideLoading();
                    } else {
                        this.$u.toast(res.msg);
                        uni.hideLoading();
                    }
                });
            }
            that.closeSkuPopup();
        },

        handleMenuTap(id, index) {

            var _this = this;
            this.currentCateId = id;
            this.needCurrentCateId = id;

            this.menuChilds = [];
            this.menuChilds = _this.menus[index].child;

            this.childCurrent = 0;
            this.$forceUpdate()

            this.page = 1;
            this.goodsList = [];
            this.getGoods(0);

        },

        clickChange(e) {
            this.childCurrent = e.index;
            if (e.id != 0) {
                this.needCurrentCateId = e.id;
            } else {
                this.needCurrentCateId = this.currentCateId;
            }
            this.page = 1;
            this.goodsList = [];
            this.getGoods();
        },
        scrolltolower() {
            console.log("触底了");
            if (this.loadStatus != 'nomore') {
                this.getGoods();
            }
        },
        //取得商品数据
        getGoods: function () {
            uni.showLoading({
                title: '加载中'
            });
            var _this = this;
            let data = {
                page: this.page,
                limit: this.limit,
            };
            var where = {
                catId: this.needCurrentCateId,
            };
            data.where = JSON.stringify(where);
            _this.$u.api.goodsList(data).then(res => {
                if (res.status) {
                    const _list = res.data.list;
                    _this.goodsList = [..._this.goodsList, ..._list];
                    if (res.data.totalPages >= _this.page) {
                        _this.loadStatus = 'loadmore';
                        _this.page++;
                    } else {
                        // 数据已加载完毕
                        _this.loadStatus = 'nomore';
                    }
                    uni.hideLoading();
                } else {
                    // 接口请求出错了
                    uni.hideLoading();
                    this.$u.toast(res.msg);
                }
            });
        },
        // 获取购物车数量
        getCartNums() {
            let userToken = this.$db.get("userToken");
            if (userToken && userToken != '') {
                // 获取购物车数量
                this.$u.api.getCartNumAndMoney().then(res => {
                    if (res.status) {
                        this.cartNums = res.data.count;
                        this.cartMoney = res.data.money;
                        console.log(this.cartNums);
                    }
                })
            }
        },
    }
}
</script>
<style lang="scss" scoped>
@import "index.scss";
</style>
